#include "batterywidget.h"
BatteryWidget::BatteryWidget(QWidget *parent)
    : QWidget(parent), batteryLevel(100)
{
   // setFixedSize(60, 30); // 设置控件固定大小
}
void BatteryWidget::setBatteryLevel(int level)
{
    if (level < 0)
        level = 0;
    if (level > 100)
        level = 100;
    batteryLevel = level;
    update(); // 触发重绘
}

void BatteryWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 绘制边框
    QRectF borderRect(1, 1, width() - 8, height() - 2);
    painter.setPen(QPen(Qt::white, 2)); // 边框宽度和颜色
    painter.setBrush(Qt::NoBrush);
    painter.drawRoundedRect(borderRect, 3, 3); // 边框圆角

    // 绘制电池外壳
    QRectF batteryRect(4, 4, width() - 14, height() - 8);
    painter.setBrush(Qt::transparent);
    painter.setPen(Qt::NoPen);
    painter.drawRoundedRect(batteryRect, 3, 3); // 电池圆角

    // 绘制电量
    QRectF levelRect(batteryRect.left(), batteryRect.top(), (batteryRect.width()) * batteryLevel / 100.0, batteryRect.height());
    QColor levelColor = (batteryLevel < 20) ? Qt::red : Qt::green;
    painter.setBrush(levelColor);
    painter.drawRoundedRect(levelRect, 3, 3);

    // 绘制电量百分比
    QString levelText = QString::number(batteryLevel);
    painter.setPen(Qt::white);
    painter.setBrush(Qt::NoBrush);
    QFont font = painter.font();
    font.setBold(true);
    painter.setFont(font);
    painter.drawText(batteryRect, Qt::AlignCenter, levelText);

    // 绘制电池头（在边框外面）
    QRectF batteryHeadRect(width() - 5, height()/ 4, 3, height()/ 2);
    painter.setBrush(Qt::white);
    painter.setPen(Qt::NoPen);
    painter.drawRoundedRect(batteryHeadRect, 2, 2); // 电池头圆角
}
